package middleware

import (
	"fmt"
	"log"
	"time"

	"github.com/gin-gonic/gin"
)

func Logger() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 请求前
		start := time.Now()

		// 处理请求
		c.Next()

		// 请求后
		latency := time.Since(start)
		status := c.Writer.Status()

		// 查看请求参数类型位置
		req := c.Request
		contentType := req.Header.Get("Content-Type")
		if contentType == "application/x-www-form-urlencoded" || contentType == "multipart/form-data" {
			fmt.Println("请求参数在请求体中")
		} else if contentType == "application/json" {
			fmt.Println("请求参数在请求头中")
		}

		// 打印请求日志
		log.Printf("[GIN] %v | %3d | %12v | %s | %-7s %s  \n",
			start.Format("2006/01/02 - 15:04:05"),
			status,
			latency,
			c.ClientIP(),
			c.Request.Method,
			c.Request.URL.String(),
			// c.Request.Header,
		)
	}
}
